package com.pitop.base.interceptor;

import com.pitop.core.tools.JwtToken;
import com.pitop.setting.entity.Setting;
import com.pitop.setting.service.SettingSVImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截token的验证，过滤已经获得token的请求
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private SettingSVImpl settingSVImpl;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        log.debug("token >> " + token);
        if (StringUtils.isBlank(token)) {
            return false;
        }

        String token_Secret = settingSVImpl.loadByK(Setting.Key.Token_Secret.name()).getV();
        //验证token合法性
        boolean isToken = JwtToken.verifier(token, token_Secret);
        if (!isToken) {
            return false;
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }


}